var express=require('express');
var Mysqldb=require("../../../db/Mysqldb.js");
var router = express.Router();   //可使用 express.Router 类创建模块化、可挂载的路由句柄
const jwt= require('jsonwebtoken');
const expressJwt = require('express-jwt');
const nodeExcel = require('excel-export');
var Excel = require('exceljs');
const path = require('path');
var secret = 'cxcx';
var fs = require('fs');
var  multer=require('multer');
const { logger } = require('../../../logger.js');
const Msdb = require('../../../db/Msdb.js');
//后端版本v1

//通用select数据源方法
router.post('/getselectdata',async function(req,res){
	var db=new Mysqldb();
//console.log(JSON.stringify(req.body))
	var result=await db.query(`select ${req.body.value} value,${req.body.text} text from ${req.body.table} where ${req.body.text} like '%${req.body.searchText}%' limit 10 `);	
	console.log(result);
	res.send(JSON.stringify(result));
});

//通用select数据源方法
router.post('/getscaninfo',async function(req,res){
   var db=new Mysqldb();
//console.log(JSON.stringify(req.body))
   var result=await db.query("select * from machine_list where barcode='"+req.body.scanvalue+"'  and sfsj='是' "); 
   console.log(result);
   res.send(JSON.stringify(result));
});



/**
 * 导出通用excel
 */
router.post('/export_select_auto', async function (req, res) {
   var db = new Msdb();
   var timestamp = new Date().getTime();
   console.log(req.body)
   var data = req.body.exceldata;
   var columnsarr = req.body.columnarr.map(obj => {
      if ('title' in obj) {
         const { title: oldValue, ...rest } = obj;
         return { header: oldValue, ...rest };
      } else {
         return obj;
      }
   });

   var filename = req.body.filename;
   var start_time = new Date();
   const filenamettt = `./dist2/oaexcelfile/${filename}.xlsx`;
   console.log(filenamettt)
   var workbook = new Excel.stream.xlsx.WorkbookWriter({
      filename: filenamettt,
      useStyles: true,  // 启用样式

   });
   var worksheet = workbook.addWorksheet('Sheet');

   worksheet.columns = columnsarr
   var length = data.length;
   // 当前进度
   var current_num = 0;
   var time_monit = 400;
   var temp_time = Date.now();
   logger.info('开始添加数据');
   // 开始添加数据
   for (let i in data) {
      worksheet.addRow(data[i])
      current_num = i;
      if (Date.now() - temp_time > time_monit) {
         temp_time = Date.now();
         logger.info((current_num / length * 100).toFixed(2) + '%');
      }
   }
   logger.info('添加数据完毕：', (Date.now() - start_time));

   const row = worksheet.getRow(1);
   row.eachCell((cell) => {
      cell.font = {
         bold: true, // 加粗字体
         color: { argb: 'FF061178' }, // 设置为蓝色
      };
   });

   worksheet.commit();
   workbook.commit();
   var end_time = new Date();
   var duration = end_time - start_time;
   logger.info('用时：' + duration);
   logger.info("程序执行完毕");
   res.send(JSON.stringify({
      url: "http://111.77.154.58:2233/oaexcelfile/" + filename + ".xlsx"
   }));
});



// 文件上传相关配置
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    //cb(null, '../opt/upFiles/') 配合jeecgboot才使用
   cb(null, './uploads/')
}, 
filename: function (req, file, cb) {
  console.log(file)
   var fileFormat = (file.originalname).split(".");
   cb(null,  Date.now() + "-" +file.originalname);
}
});  
var upload = multer({
 storage: storage
});






 //通用附件上传方法
router.post('/uploadfs',upload.single('files[]'), function(req,res){
   console.log(req.file);
  console.info("上传文件名"+req.file.filename);
  res.send(JSON.stringify(req.file));
});




 //通用多附件上传方法
router.post('/uploadfsmulti',upload.array('培训现场图片'), function(req,res){
 // console.info("重命名字符串"+req.body.renamestr);
  var returnfilenames_arr=[];
  req.files.forEach((obj) => {
     returnfilenames_arr.push(obj.filename)
  });
  var returnfilenames_str=returnfilenames_arr.toString();
  res.send(returnfilenames_str);
});

function findProjectRoot(startPath = __dirname) {  
   let currentPath = startPath;  
   const rootPath = path.parse(startPath).root;  
   
   while (currentPath !== rootPath) {  
     const packageJsonPath = path.join(currentPath, 'package.json');  
     if (fs.existsSync(packageJsonPath)) {  
       return currentPath;  
     }  
     currentPath = path.dirname(currentPath);  
   }  

   // 如果没有找到package.json文件，则返回一个错误  
   throw new Error('Unable to find project root (package.json)');  
 } 

 //通用多附件上传方法
 router.delete('/deleteFile',async function(req,res){
   console.log(req.body.file)
   const filename = req.body.file;
   console.log(findProjectRoot());
   const uploadDir = path.join(findProjectRoot(), 'uploads');
   const filePath = path.join(uploadDir, filename);
   console.log(filePath);
   try {  
      // 检查文件是否存在  
      if (fs.existsSync(filePath)) {  
        // 删除文件  
        fs.unlinkSync(filePath);  
        res.status(200).send(`File ${filename} deleted successfully`);  
      } else {  
        res.status(404).send(`File ${filename} not found`);  
      }  
    } catch (error) {  
      res.status(500).send(`Error deleting file ${filename}: ${error.message}`);  
    }  
  });



module.exports = router; 